package cn.kow.kmall.controller.content;

import cn.kow.kmall.admin.pojo.vo.ContentModuleItemVO;
import cn.kow.kmall.admin.pojo.vo.ContentModuleVO;
import cn.kow.kmall.common.enums.ContentModuleTypeEnum;
import cn.kow.kmall.controller.BaseController;
import cn.kow.kmall.core.response.KmallResult;
import cn.kow.kmall.pojo.dto.ContentQueryDTO;
import cn.kow.kmall.pojo.entity.ContentModule;
import cn.kow.kmall.pojo.entity.ContentModuleItem;
import cn.kow.kmall.service.ContentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: lijun
 * @Description:
 * @Date: Created in 2020-04-28 16:35
 * @Modified By:
 */
@Slf4j
@RestController
@RequestMapping("/content")
public class ContentController extends BaseController {

    @Autowired
    private ContentService contentService;

    @PostMapping(value = "/list")
    public KmallResult list(@RequestBody ContentQueryDTO queryDTO) {
        Page<ContentModule> page = contentService.listByPage(queryDTO);
        return KmallResult.success().put("rows", page.getContent())
                .put("total", page.getTotalElements());
    }

    @PostMapping("/del")
    public KmallResult remove(@RequestBody Long[] ids) {
        contentService.deleteModule(Arrays.asList(ids));
        return KmallResult.success();
    }

    @PostMapping(value = "/subject/list")
    public KmallResult subjectList(@RequestBody ContentQueryDTO queryDTO) {
        queryDTO.setModuleType(ContentModuleTypeEnum.SUBJECT.getType());
        Page<ContentModule> page = contentService.listByPage(queryDTO);
        return KmallResult.success().put("rows", page.getContent())
                .put("total", page.getTotalElements());
    }

    @GetMapping(value = "/subject/{id}")
    public KmallResult subjectInfo(@PathVariable Long id) {
        ContentModule module = contentService.getById(id);
        List<ContentModuleItem> itemList = contentService.listModuleItem(id);

        ContentModuleVO moduleVO = new ContentModuleVO();
        BeanUtils.copyProperties(module, moduleVO);
        if (CollectionUtils.isNotEmpty(itemList)) {
            List<ContentModuleItemVO> itemVOList = itemList.stream().map(a -> {
                ContentModuleItemVO itemVO = new ContentModuleItemVO();
                BeanUtils.copyProperties(a, itemVO);
                return itemVO;
            }).collect(Collectors.toList());
            moduleVO.setItemList(itemVOList);
        }
        return KmallResult.success(moduleVO);
    }
}
